import qualified Data.Map as Map

data Direction = L | R deriving (Show, Eq)
type PathMap = Map String (String, String)

char2Direction :: Char -> Direction
char2Direction c = 
    case c of
        'L' -> L
        'R' -> R
         _  -> error "No direction!"

getDirections :: [String] -> [Direction]
getDirections = map char2Direction . head

getMap :: [String] -> PathMap
getMap = Map.fromList . map parseLine . drop 2
    where
        parseLine :: String -> (String, (String, String))
        parseLine line = (name, (left, right))
        where
            name  = take 3 cs
            left  = take 3 . drop 7 $ line
            right = take 3 . drop 12 $ line

step :: PathMap -> String -> Direction -> String
step nodeMap nodeName direction = 
    | direction == L = fst $ node
    | direction == R = snd $ node
    where
        node = nodeMap Map.! nodeName

countSteps :: PathMap -> String -> [Direction] -> Int
countSteps _ "ZZZ" _  = 0
countSteps nodeMap nodeName (d:ds) = 1 + countSteps nodeMap nodeName' ds
    where
        nodeName' = step nodeMap nodeName d

main = do
    contents <- readFile "input.txt"

    let directions = cycle . getDirections . lines $ contents
    let nodeMap = getMap . lines $ contents

    print $ countSteps nodeMap "AAA" directions
